package com.ibiz.znjd.znjd;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.ibiz.znjd.MainApplication;
import com.ibiz.znjd.baidu.location.GeoFenceConfig;
import com.ibiz.znjd.baidu.location.GeoFenceService;
import com.ibiz.znjd.baidu.location.LocationUtils;

import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 预警相关工具类
 */
public class WaringUtil {
    /**
     * 时间间隔5分钟
     */
    static long TimeInterval = 1000*60*5;

    /**
     * 上一次越界时间
     */
    static long lastWarningTime = 0;

    /**
     * 电子围栏配置
     */
    static GeoFenceConfig geoFenceConfig = null;

    /**
     * 监管开始时间
     */
    static long startStamp = 0;

    /**
     * 监管结束时间
     */
    static long endStamp = 0;

    /**
     * 发送越界预警信息
     * @param app
     * @param location
     * @param yjlx 预警类型，越界： 10，入界：40
     */
    public static void sendYjWarining(MainApplication app, BDLocation location, String yjlx){
        // 触发一次越界后，五分钟内不会再触发越界
        long current = new Date().getTime();
        if(lastWarningTime != 0 && (current - lastWarningTime) < TimeInterval ){
            return;
        }
        lastWarningTime = current;

        // 把gcj02坐标系的转换成bd09ll坐标系
        LatLng desLatLng = LocationUtils.converter(location);

        String warningUrl = app.envMap.get("warningUrl");
        String token = app.envMap.get("token");
        String personid = app.envMap.get("personid");
        if( warningUrl == null || token == null || personid == null){
            return;
        }

        // 当前时间
        Date date = new Date();
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        String time = sdf.format(date);

        // 发起请求
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        JSONObject json = new JSONObject();
        try {
            json.put("personid", personid);
            json.put("yjsj", time);
            json.put("yjlx", yjlx);
            json.put("lat", desLatLng.latitude);
            json.put("lng", desLatLng.longitude);
            json.put("yjdd", location.getAddrStr());
        }catch (Exception e){
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(JSON,json.toString());
        Request request = new Request.Builder()
                .header("Authorization", "Bearer " + token)
                .header("deviceType", "app ")
                .url(warningUrl)
                .post(body)
                .build();
        Call call = client.newCall(request);

        // 请求回调
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("上传越界预警失败！");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                if(response.isSuccessful()){
                    //处理UI需要切换到UI线程处理
                    System.out.println("上传越界预警成功：");
                }else{
                    System.out.println("上传越界预警失败：");
                }
                System.out.println(result);
            }
        });
    }

    /**
     * 设置电子围栏
     * @param config
     */
    public static void setGeoFenceConfig(GeoFenceConfig config, MainApplication app){
        if(!inPeriod(app)) return;
        if(null == geoFenceConfig){
            geoFenceConfig = config;
            app.geoFenceService = new GeoFenceService(app, config);
        }else{
            if(!geoFenceConfig.isSame(config) && null != app.geoFenceService){
                app.geoFenceService.removeGeoFence();
                app.geoFenceService = new GeoFenceService(app, config);
            }
        }
    }

    /**
     * 设置监管开始时间和结束时间
     * @param start
     * @param end
     */
    public static void setStartAndEnd(String start, String end){
        if(null==start || null == end){
            return;
        }
        // 日期格式化
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        try {
            startStamp = sdf.parse(start).getTime();
            endStamp = sdf.parse(end).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 是否在监管时间范围内
     * @return
     */
    public static boolean inPeriod(MainApplication app){
        // 监管方式不为20时,关闭手机的围栏功能
        String jgfs = app.envMap.get("jgfs");
        if(!"20".equals(jgfs)){
            System.out.println("监管方式为"+jgfs+",不设置围栏");
            return false;
        }
        long timestamp = new Date().getTime();
        // 开始，结束时间不存在时。或者当前时间小于开始时间，当前时间大于结束时间。
        return !(endStamp == 0 || startStamp == 0 || timestamp < startStamp || endStamp < timestamp);
    }

    /**
     * 根据当前时间做对应的处理
     */
    public static void updateCurrentTime(MainApplication app){
        if(inPeriod(app)){
            // 在监管范围内，且服务没生成的生成之
            if(null == app.geoFenceService && null != geoFenceConfig ){
                // 在开始监管时间到达后初始化围栏服务（当没有围栏服务时）
                app.geoFenceService = new GeoFenceService(app, geoFenceConfig);
            }
        }else{
            // 不在监管时间范围内的时候，如果有服务，关闭之
            if(null != app.geoFenceService){
                // 监管时间结束后，停止围栏。
                app.geoFenceService.removeGeoFence();
                app.geoFenceService = new GeoFenceService(app, geoFenceConfig);
            }
        }
    }

}
